#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/generic/apis/weixin_qy/send_message.py
# Compiled at: 2017-11-16 15:44:28
"""
Copyright © 2012-2017 Tencent BlueKing. All Rights Reserved. 蓝鲸智云 版权所有
"""
import json
from django import forms
from common.constants import API_TYPE_OP
from components.component import Component, SetupConfMixin
from common.forms import BaseComponentForm, ListField
from .toolkit import configs, tools

class SendMessage(Component, SetupConfMixin):
    sys_name = configs.SYSTEM_NAME
    api_type = API_TYPE_OP

    class Form(BaseComponentForm):
        corpid = forms.CharField(label=u'企业ID', required=True)
        corpsecret = forms.CharField(label=u'应用的凭证密钥', required=True)
        agentid = forms.IntegerField(label=u'企业应用的ID', required=True)
        touser = ListField(label=u'接收者', required=True)
        content = forms.CharField(label=u'消息内容', required=True)

    def get_wx_access_token(self, params):
        wx_token = self.invoke_other('generic.weixin_qy.get_token', kwargs=params)
        return wx_token['data']['access_token']

    def handle(self):
        access_token = self.get_wx_access_token(params=self.form_data)
        data = {'touser': ('|').join(self.form_data['touser']),
           'msgtype': 'text',
           'agentid': self.form_data['agentid'],
           'text': {'content': self.form_data['content']
                    }
           }
        wx_client = tools.WEIXINClient(self.outgoing.http_client)
        result = wx_client.post(path='/cgi-bin/message/send?access_token=%s' % access_token, data=json.dumps(data, ensure_ascii=False).encode('utf-8'))
        if result['result']:
            invaliduser = result.get('data', {}).get('invaliduser')
            if invaliduser:
                self.response.payload = {'result': False,'message': u'微信消息发送失败，无效用户：%s' % invaliduser}
            else:
                self.response.payload = {'result': True,'message': u'微信消息发送成功。'}
        else:
            ret_data = result.get('data', {})
            message = u'微信消息发送失败'
            if ret_data.get('invaliduser'):
                message = u'%s，无效用户：%s' % (message, ret_data['invaliduser'])
            if ret_data.get('errmsg'):
                message = u'%s，%s' % (message, ret_data['errmsg'])
            self.response.payload = {'result': False,'message': message,
               'data': result,
               'params': data
               }
